package com.xu.cloud.auth.interceptor;

import com.xu.cloud.auth.service.AccessTokenService;
import com.xu.cloud.common.auth.AuthContext;
import com.xu.cloud.common.auth.AuthContextHolder;
import com.xu.cloud.common.constant.HttpConstant;
import com.xu.cloud.common.util.ResourceUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.LogicalHandler;

/**
 * AccessToken认证拦截器
 *
 * @author xuguan
 * @since 2025/2/23
 */
@Slf4j
@RequiredArgsConstructor
public class AccessTokenAuthInterceptor implements HandlerInterceptor {

    private final AccessTokenService accessTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("AccessToken认证拦截器前置执行开始");
        final String path = request.getRequestURI();
        if (ResourceUtil.isStatic(path) || ResourceUtil.isOpenUrl(path)) {
            log.info("开放接口path=[{}], 无需认证", path);
            return true;
        }

        final String accessToken = request.getHeader(HttpHeaders.AUTHORIZATION);
        final AuthContext authContext = accessTokenService.resolveAndExtendAccessToken(accessToken);
        AuthContextHolder.setAuthContext(authContext);
        log.info("AccessToken认证拦截器前置执行结束, 解析续期AccessToken成功");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        AuthContextHolder.removeAuthContext();
        log.info("AccessToken认证拦截器最终执行结束, 清空AuthContextHolder成功");
    }
}
